'use strict';
import React, { Component } from 'react';
import {
    View, StyleSheet, Text, Clipboard, CameraRoll,
    Dimensions, ScrollView, TouchableHighlight, TextInput,
    Modal, TouchableOpacity, Button, Animated, Alert
} from 'react-native';
import { connect } from 'react-redux';

import Toast, { DURATION } from 'react-native-easy-toast';

import QRComponent from '../components/QRCode';
import CommonTitleBar from '../components/CommonTitleBar';
import { scaleSize, scaleFontSize } from '../util/size';
import NccButton from '../components/Button';
import { request } from '../util';
import { utilGetAvailableByCoinType, utilGetAddressByCoinType } from '../util/balanceUtil';
import { Global, API_MAP, TOAST_MESSAGE } from '../util/constants';
import { IReduxUserInfo, IReduxBalanceInfo, INavigation } from '../interface';


const { width: deviceWidth, height: deviceHeight } = Dimensions.get('window');

import { captureScreen } from "react-native-view-shot";
import { utilValidCheck } from '../util/validCheck';
import * as balanceAction from '../actions/balance';

const VERIFY_CODE_TIME = Global.verifyCodeTime;;
const VERIFY_CODE_TEXT = '获取验证码';


interface IState {
    activeTab: string,
    currentCoinType: string,
    extratAddress: string,
    extratAmount: string | number,
    modalVisible: boolean,
    verifyCodeStatus: string,
    verifyCodeTime: number,
    fadeAnim: Animated.Value,
    verifyCode: string,
}

interface IProps {
    user: IReduxUserInfo,
    balance: IReduxBalanceInfo,
    navigation: INavigation,
    updateBalanceInfo: Function,
}

class DepositAndWithdrawView extends Component<IProps, IState> {
    constructor(props) {
        super(props);
        this.state = {
            activeTab: 'deposit',
            currentCoinType: 'BTC',
            extratAddress: '',
            extratAmount: '',
            modalVisible: false,
            verifyCodeStatus: VERIFY_CODE_TEXT,
            verifyCodeTime: VERIFY_CODE_TIME,
            fadeAnim: new Animated.Value(-deviceWidth),
            verifyCode: '',
        }
    }

    componentDidMount() {
        const { navigation } = this.props;
        const coinType: string = navigation.getParam('coinType', 'BTC');
        const tab: string = navigation.getParam('tab', 'deposit');
        this.setState({
            activeTab: tab,
            currentCoinType: coinType,
        })
    }

    componentWillUnmount () {
        console.log('componentWillUnmount...??>');
        this.setState({modalVisible: false});
    }

    _setClipboardContent = async () => {
        try {
            await Clipboard.getString();
            this.refs.toast.show('copyed');
        } catch (e) {
            console.error('e', e);
        }
    }

    onCapture = uri => {
        console.warn("do something with ", uri);
    }

    toastMessage(msg: string) {
        console.log('toastMessage???', msg);
        this.refs.toast.show(msg);
    }

    // ------- top Tab
    updateActiveTab = (tabName: string) => {
        this.setState({ activeTab: tabName });
    }

    onChangeAddress = (value) => {
        this.setState({ extratAddress: value });
    }

    onChangeAmount = (value) => {
        this.setState({ extratAmount: value });
    }

    onChangeVerifyCode = (value) => {
        this.setState({verifyCode: value});
    }

    reloadUserBalanceData = () => {
        request(API_MAP.balance, {
            method: 'post',
            data: {bankName: 'coinxp.bank'}
        }, false, (err, res) => {
            if (err) {
                return null;
            }
            if (res.retCode == '00') {
                this.props.updateBalanceInfo(res.data);
            }
        })
    }

    checkValidOfAddr = (coinType, addr) => {
        switch (coinType) {
            case 'BTC': {
                return /^1[0-9a-zA-Z]{33}$|^\w{34}$/.test(addr)
            }
            case 'ETH': {
                return /^0x[0-9a-fA-F]{40}$/.test(addr)
            }
            default: {
                return false;
            }
        }
    }

    handleExtractToConfirm = () => {
        const { extratAddress: userCoinAddr, extratAmount: amount, currentCoinType: coinType } = this.state;
        if (!this.checkValidOfAddr(coinType, userCoinAddr)) {
            return this.toastMessage(TOAST_MESSAGE.INVALID_ADDR);
        }

        if (!utilValidCheck(amount, 'amount')) {
            return this.toastMessage(TOAST_MESSAGE.INVALID_AMOUNT);
        }

        let available = utilGetAvailableByCoinType(this.props.balance, coinType);
        if (amount > available) {
            return this.toastMessage(TOAST_MESSAGE.BALANCE_NOT_ENOUGH);
        }
        this.setState({ modalVisible: true });
        return;
    }

    handleExtract = () => {
        const { extratAddress: userCoinAddr, extratAmount: amount, currentCoinType: coinType, verifyCode} = this.state;

        // 在这里验证参数 
        if (!this.checkValidOfAddr(coinType, userCoinAddr)) {
            return this.toastMessage(TOAST_MESSAGE.INVALID_ADDR);
        }

        if (!utilValidCheck(amount, 'amount')) {
            return this.toastMessage(TOAST_MESSAGE.INVALID_AMOUNT);
        }

        if (!utilValidCheck(verifyCode, 'verifyCode')) {
            return this.toastMessage(TOAST_MESSAGE.INVALID_CODE);
        }

        console.log('userCoinAddr, amount, coinType', userCoinAddr, amount, coinType);
        // coinType = COINTYPE_MAP_NUM[coinType];
        if (coinType == undefined) {
            this.toastMessage(TOAST_MESSAGE.INVALID_TYPE);
            return;
        }

        request(API_MAP.draw, {
            method: 'post',
            data: {
                userCoinAddr, 
                amount: Number(amount),
                coinType,
                code: verifyCode,
            }
        }, false, (err, res) => {
            if (err) {
                return this.toastMessage(TOAST_MESSAGE.AGAIN_LATER);
            }
            if (res.retCode === '00') {
                this.toastMessage(TOAST_MESSAGE.EXTRACT_SUCCESS);
                this.setState({ verifyCodeStatus: VERIFY_CODE_TEXT, modalVisible: false, verifyCodeTime: Global.verifyCodeTime });
                this.reloadUserBalanceData();
            } else {
                return this.toastMessage(res.retMsg);
            }
        });
        // 重新加载当前的余额
    }

    updateVerifyCodeStatus = () => {
        let {verifyCodeTime} = this.state;
        if (verifyCodeTime === 0) {
            this.setState({verifyCodeStatus: VERIFY_CODE_TEXT, verifyCodeTime: VERIFY_CODE_TIME});
            return;
        } 
        verifyCodeTime --;
        this.setState({verifyCodeTime: verifyCodeTime, verifyCodeStatus: `重试 (${verifyCodeTime} s)`});
        setTimeout(() => {
            this.updateVerifyCodeStatus();
        }, 1000);
    }

    getVerifyCode = () => {
        let { verifyCodeTime } = this.state;

        if (verifyCodeTime < VERIFY_CODE_TIME) {
            return;
        }

        const userInfo = this.props.user;
        request(API_MAP.verifyCode, {
            method: 'post',
            data: {
                mobile: userInfo.name,
                type: 'extract'
            }
        }, false, (err, res) => {
            if (res.retCode == '00') {
                Alert.alert(res.data.code);
                this.updateVerifyCodeStatus();
            } else if (res.retCode == '03') {
                Alert.alert(res.retMsg);
            } else {
                Alert.alert(TOAST_MESSAGE.AGAIN_LATER);
            }
        })

    }

    renderTopOptionBtn = () => {
        let { activeTab } = this.state;
        let topDepositStyle; //= styles.activeOptionBtn;
        let topWithdrawStyle; // = styles.inactiveOptionBtn;

        if (activeTab === 'withdraw') {
            topDepositStyle = styles.inactiveOptionBtn;
            topWithdrawStyle = styles.activeOptionBtn;
        } else {
            topDepositStyle = styles.activeOptionBtn;
            topWithdrawStyle = styles.inactiveOptionBtn;
        }

        return (
            <View style={{
                display: 'flex',
                flexDirection: 'row',
                backgroundColor: 'white',
                paddingBottom: scaleSize(11),
                alignItems: 'center',
                justifyContent: 'center',
            }}>
                <TouchableHighlight onPress={() => {
                    this.updateActiveTab('deposit');
                }}>
                    <Text style={[styles.topOptionBtn, {
                        borderTopLeftRadius: scaleSize(2),
                        borderBottomLeftRadius: scaleSize(2),
                    }, topDepositStyle
                    ]} >
                        充币
                    </Text>
                </TouchableHighlight>

                <TouchableHighlight onPress={() => {
                    this.updateActiveTab('withdraw');
                }}>
                    <Text style={[
                        styles.topOptionBtn, {
                            borderBottomRightRadius: scaleSize(2),
                            borderTopRightRadius: scaleSize(2),
                        }, topWithdrawStyle
                    ]} >
                        提币
                    </Text>
                </TouchableHighlight>
            </View>
        )
    }

    ///-----------------

    ///  ---- renderContent , withDrawPage or depositPage 
    renderContent = () => {
        let { activeTab } = this.state;
        if (activeTab === 'deposit') {
            return this.renderDepositContent();
        }
        return this.renderWithdrawContent();
    }

    renderDepositContent = () => {
        let { currentCoinType: coinType } = this.state;
        const address = utilGetAddressByCoinType(this.props.balance, coinType);
        Clipboard.setString(address);

        return (

            <View style={{
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'center',
                marginTop: scaleSize(8),
                alignItems: 'center',
                height: scaleSize(deviceHeight - 120),
                // backgroundColor: 'red',
            }}>
                <ScrollView style={{
                    // minHeight: scaleSize(795),
                    height: scaleSize(800),
                }}>

                    <View style={{
                        display: 'flex',
                        width: scaleSize(335),
                        backgroundColor: '#FFFFFF',
                        justifyContent: 'center',
                        paddingBottom: scaleSize(20),
                    }}>
                        <View style={{
                            flexDirection: 'row',
                            width: scaleSize(335),
                            justifyContent: 'center',
                            alignItems: 'center',
                            marginTop: scaleSize(8),
                        }}>
                            <Text style={{
                                fontFamily: 'PingFangSC-Medium',
                                fontSize: scaleSize(20),
                                color: '#4869EE',
                            }}> {coinType}
                            </Text>
                        </View>

                        <View style={{
                            display: 'flex',
                            justifyContent: 'center',
                            alignItems: 'center',
                            marginTop: scaleSize(29),
                        }}>
                            <View style={{
                                width: scaleSize(184),
                                height: scaleSize(184),
                            }}>
                                {
                                    address ? (<QRComponent value={address} size={scaleSize(161)} />) : (
                                        <Text style={{
                                            textAlign: 'center'
                                        }}> 暂无 地址 </Text>
                                    )
                                }

                            </View>
                        </View>

                        <View style={{
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center'
                        }}>
                            <NccButton text={'保存图片'} textStyle={{
                                fontFamily: 'PingFangSC-Regular',
                                fontSize: scaleFontSize(13),
                                color: '#FFFFFF',
                                textAlign: 'center',
                                width: scaleSize(112),
                                height: scaleSize(28),
                                lineHeight: scaleSize(28),
                            }}
                                buttonStyle={{
                                    width: scaleSize(112),
                                    height: scaleSize(28),
                                    borderRadius: scaleSize(100),
                                    backgroundColor: '#4F6AE5',
                                    marginTop: scaleSize(10),
                                }}
                                onPress={this.saveImage}
                            />
                            <Text style={{
                                marginTop: scaleSize(32),
                                lineHeight: scaleSize(17),
                                textAlign: 'center',
                                fontFamily: 'PingFangSC-Semibold',
                                fontSize: scaleSize(12),
                                color: '#4A4A4A',
                                letterSpacing: 0.6
                            }}>
                                {address}
                            </Text>

                            <NccButton text={'复制地址'}
                                textStyle={{
                                    fontFamily: 'PingFangSC-Regular',
                                    fontSize: scaleFontSize(13),
                                    color: '#FFFFFF',
                                    textAlign: 'center',
                                    width: scaleSize(112),
                                    height: scaleSize(28),
                                    lineHeight: scaleSize(28),
                                }}
                                buttonStyle={{
                                    width: scaleSize(112),
                                    height: scaleSize(28),
                                    borderRadius: scaleSize(100),
                                    backgroundColor: '#4F6AE5',
                                    marginTop: scaleSize(10),
                                }}
                                onPress={this._setClipboardContent}
                            />

                        </View>


                    </View>
                    <View style={{
                        marginTop: scaleSize(4),
                        width: scaleSize(335),
                        marginBottom: scaleSize(5),
                        backgroundColor: '#FFFFFF',
                        paddingTop: scaleFontSize(22),
                        paddingLeft: scaleSize(18),
                        paddingRight: scaleSize(18),
                        paddingBottom: scaleSize(18),
                        // height: scaleSize(200),
                    }}>
                        <View>
                            <Text style={styles.tip}>· 请勿向上述地址充值任何非BTC资产，否则资产将不可找回。</Text>
                            <Text style={styles.tip}>· 您充值至上述地址后，需要整个网络节点的确认，一次网络确认后到账，6次网络确认后可提币。</Text>
                            <Text style={styles.tip}>· 最小充值金额0.001 BTC，小于最小金额的充值将不会上账。</Text>
                            <Text style={styles.tip}>· 您的充值地址不会经常改变，可以重复充值，如有更改，我们会尽量通过网站公告或邮件通知您。</Text>
                            <Text style={styles.tip}>· 请务必确认电脑及浏览器安全，防治信息被篡改或泄露。</Text>
                        </View>
                    </View>
                </ScrollView>
            </View>
        )
    }

    renderWithdrawContent = () => {
        let { currentCoinType: coinType } = this.state;
        let available = utilGetAvailableByCoinType(this.props.balance, coinType);
        return (
            <View style={{
                marginTop: scaleSize(8),
                height: deviceHeight - 150,
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'space-between',
                alignItems: 'center',
            }}>
                {/* <View style={{
                // flex: 1,
                backgroundColor: 'rgba(0, 0, 0, 0.5)',
            }}> */}
                {/* <NccModal /> */}
                <Modal
                    visible={this.state.modalVisible}
                    animationType={"none"}
                    transparent={true}>

                    <TouchableOpacity activeOpacity={1} style={{ flex: 1 }} onPress={() => {
                        // this.updateCoinSelectViewState();
                        this.setState({ modalVisible: false });
                    }}>

                        <View style={{
                            display: 'flex',
                            flex: 1,
                            backgroundColor: 'rgba(0,0,0,0.5)'
                        }}>
                            <View style={{
                                alignSelf: 'center',
                                marginTop: scaleSize(100),
                                height: 200,
                                width: '100%',
                                backgroundColor: 'white',
                                justifyContent: 'center',
                                padding: scaleSize(20),
                            }}>
                                <Text style={[{
                                    marginTop: scaleSize(20),
                                }]}>验证码</Text>
                                <View style={{
                                    display: 'flex',
                                    flexDirection: 'row',
                                    justifyContent: 'space-between',
                                }}>
                                    <TextInput placeholder={'输入验证码'} style={[
                                        {
                                            marginTop: scaleSize(17),
                                            borderWidth: 1,
                                            width: scaleSize(200),
                                            height: scaleSize(40),
                                            borderColor: Global.grayColor,
                                            paddingLeft: scaleSize(5),
                                        }
                                    ]}
                                        onChangeText = {this.onChangeVerifyCode}
                                        keyboardType={'numeric'}
                                        underlineColorAndroid={'transparent'}
                                    ></TextInput>
                                    <Text style={{
                                        alignSelf: 'flex-end',
                                        width: scaleSize(120),
                                        height: scaleSize(40),
                                        lineHeight: scaleSize(40),
                                        textAlign: 'center',
                                    }} onPress={this.getVerifyCode}>{this.state.verifyCodeStatus}</Text>
                                </View>
                                <View style={{
                                    marginTop: scaleSize(10),
                                }}>
                                    <Button title={'确定'} onPress={this.handleExtract}></Button>
                                </View>
                            </View>
                        </View>
                    </TouchableOpacity>
                </Modal>
                {/* </View> */}
                <View style={{
                    height: deviceHeight - 220,
                }}>
                    <ScrollView style={{
                        width: scaleSize(335),
                        // height: scaleSize(330),
                    }}>
                        <View style={{
                            backgroundColor: '#FFFFFF',
                            paddingTop: scaleSize(20),
                            paddingLeft: scaleSize(16),
                            paddingRight: scaleSize(16),
                        }}>
                            <Text style={[styles.withdrawTipTitle,]}>可用</Text>
                            <Text style={{
                                marginTop: scaleSize(18),
                                fontFamily: 'Helvetica',
                                fontSize: scaleSize(18),
                                color: '#4A4A4A',
                            }}>{available} {coinType} </Text>

                            <Line />

                            <Text style={[styles.withdrawTipTitle, {
                                marginTop: scaleSize(20),
                            }]}>提币地址</Text>

                            <View>
                                <TextInput placeholder={'输入地址'} style={[
                                    styles.withdrawFontStyle,
                                    { marginTop: scaleSize(18) }
                                ]}
                                    underlineColorAndroid={'transparent'}
                                    onChangeText={this.onChangeAddress}
                                >
                                </TextInput>
                            </View>

                            <Line />

                            <Text style={[styles.withdrawTipTitle, {
                                marginTop: scaleSize(20),
                            }]}>数量</Text>
                            <View style={{
                                display: 'flex',
                                flexDirection: 'row',
                                justifyContent: 'space-between',
                            }}>
                                <TextInput placeholder={'0.0000000'} style={[
                                    styles.withdrawFontStyle,
                                    { marginTop: scaleSize(17), width: scaleSize(200) }
                                ]}
                                    keyboardType={'numeric'}
                                    underlineColorAndroid={'transparent'}
                                    onChangeText={this.onChangeAmount}
                                ></TextInput>
                                <Text style={{
                                    alignSelf: 'flex-end'
                                }}>{coinType}</Text>
                            </View>

                            <Line />

                            <Text style={[styles.withdrawTipTitle, {
                                marginTop: scaleSize(16),
                            }]}>手续费</Text>

                            <View style={{
                                display: 'flex',
                                flexDirection: 'row',
                                justifyContent: 'space-between',
                                marginTop: scaleSize(16),
                                marginBottom: scaleSize(10),
                            }}>
                                <Text style={[styles.withdrawFontStyle]}>0.001</Text>
                                <Text>{coinType}</Text>
                            </View>
                        </View>


                        <View style={{
                            marginTop: scaleSize(4),
                            backgroundColor: '#FFFFFF',
                            paddingTop: scaleSize(13),
                            paddingBottom: scaleSize(13),
                            paddingLeft: scaleSize(17),
                            paddingRight: scaleSize(17),
                        }}>
                            <Text style={{
                                fontFamily: 'PingFangSC-Regular',
                                lineHeight: scaleSize(17),
                                fontSize: scaleFontSize(12),
                                color: '#4A4A4A',
                                letterSpacing: 0.6,
                            }}>
                                最小提币数量为：0.001 {this.state.currentCoinType}
                                为保证资金安全，当您账户安全策略变更、密码修改、使用新地址提币，我们会对提币进行人工审核，
                                请耐心等待工作人员电话或邮件联系。
                                请务必确认电脑及浏览器安全，防止信息被篡改或泄露。
                    </Text>
                        </View>


                    </ScrollView>
                </View>
                <View style={{
                    justifyContent: 'flex-end',
                    alignItems: 'flex-end',
                }}>
                    <NccButton text={'确定'} buttonStyle={{
                        borderRadius: scaleSize(2),
                        width: scaleSize(335),
                        height: scaleSize(44),
                        backgroundColor: '#4869EE',
                    }} onPress={() => {
                        this.handleExtractToConfirm();
                    }} />
                </View>

            </View>
        )

    }

    saveImage = () => {
        captureScreen({
            format: "png",
            quality: 0.8
        }).then(
            (uri) => {
                CameraRoll.saveToCameraRoll(uri).then((_) => {
                    alert('保存成功');
                }, (err) => {
                    console.warn('err' + err);
                })
            },
            error => console.error("Oops, snapshot failed", error)
        );
    }

    // ---------------------

    render() {
        return (
            <View style={styles.container}>
                <CommonTitleBar back={true} nav={this.props.navigation} backgroundColor={'white'} />
                <View>
                    {
                        this.renderTopOptionBtn()
                    }
                </View>
                <View>
                    {
                        this.renderContent()
                    }
                </View>
                <Toast ref='toast'
                    position='center'
                />
            </View>
        )
    }
}


export default connect(
    (state) => ({
        balance: state.balance,
        user: state.user,
    }),
    (dispatch) => ({
        updateBalanceInfo: (data) => dispatch(balanceAction.updateBalanceInfo(data)),
    })
)(DepositAndWithdrawView);


class Line extends Component {
    render() {
        return (
            <View style={{
                width: scaleSize(300),
                height: 1,
                backgroundColor: '#E2E2E2',
                marginTop: scaleSize(9.8)
            }}>
            </View>
        )
    }
}


const styles = StyleSheet.create({
    container: {
        display: 'flex',
        flexDirection: 'column'
    },
    title: {
        // position: 'absolute',
        marginTop: 50,
        height: 50
    },
    topOptionBtn: {
        height: scaleSize(32),
        width: scaleSize(70),
        fontSize: scaleFontSize(12),
        lineHeight: scaleSize(32),
        textAlign: 'center'
    },
    activeOptionBtn: {
        color: 'white',
        backgroundColor: '#4869EE',
        fontFamily: 'PingFangSC-Medium',
    },
    inactiveOptionBtn: {
        color: '#C6C6C6',
        fontFamily: 'PingFangSC-Regular',
        borderWidth: 1,
        borderColor: '#ECECEC',
    },
    tip: {
        fontFamily: 'PingFangSC-Regular',
        fontSize: scaleFontSize(12),
        color: '#4A4A4A',
        letterSpacing: 0.6,
    },
    withdrawTipTitle: {
        fontFamily: 'PingFangSC-Regular',
        fontSize: scaleSize(13),
        color: '#4A4A4A',
    },
    withdrawFontStyle: {
        fontFamily: 'Helvetica',
        fontSize: scaleSize(16),
        color: '#4A4A4A',
        height: scaleSize(30),
    }
});
